//get_post_comments_by_user
const getCommenData = {
    taskConfig: { taskStatus: false },
    savePostInfo: {},
    setting: {},
    postViewList: [],
    commentList: [],
    data: {},
    watchValue(key, newVal) {
        if (key == 'taskStatus' && newVal) {
            console.log('收集的用户数据：' + JSON.stringify(getCommenData.savePostInfo));
            Xhs.taskConfig.taskStatus = true
        }
        if (key == 'errorTask' && newVal) {
            if (newVal) {
                // 所有任务数据均执行异常
                let params = {
                    taskType: getCommenData.data.skey,
                    task_id: getCommenData.data.task_id,
                    taskName: '指定博士收集指定数量笔记的评论内容',
                    taskData: getCommenData.data,
                    errorTip: newVal,
                    taskDate: Comman.getDate()
                }
                Xhs.errorTask(params)
                getCommenData.taskConfig.taskStatus = true
            }
        }
    },
    init(data) {
        getCommenData.setting = data.setting || {}
        getCommenData.data = data || {}
        getCommenData.postViewList = []
        getCommenData.savePostInfo = {}
        getCommenData.taskConfig = Comman.defineReactive(
            {
                taskStatus: false,
                errorTask: '',
            },
            '',
            getCommenData.watchValue
        )
        getCommenData.openTask()
    },
    start(data) {
        //初始化数据
        getCommenData.init(data)
    },
    openTask() {
        let homeMnue = btnConfig.home.homeMnue
        let homeBtn = btnConfig.home.homeBtn
        let searchIconBtn = btnConfig.home.searchIconBtn
        //重置首页
        while (!depth(homeMnue.options.depth).id(homeMnue.options.id).exists()) {
            back();
            console.log('back...');
            sleep(2000);
        }
        //点击首页
        let nowHomeBtn = homeBtn.default()
        if (!nowHomeBtn) {
            console.log('首页按钮不存在，请检查并手动复原首页重新启动');
            getCommenData.taskConfig.errorTask = '首页按钮不存在'
            return
        }
        if (nowHomeBtn.bounds) {
            App.clickByBtn(nowHomeBtn, 5)
        } else {
            App.click(homeBtn.position.x, homeBtn.position.y, 5)
        }
        //点击搜索图标按钮
        let nowSearchIconBtn = searchIconBtn.default()
        if (!nowSearchIconBtn) {
            console.log('搜索图片不存在，并手动复原重新启动');
            getCommenData.taskConfig.errorTask = '首页按钮不存在'
            return
        }
        if (nowSearchIconBtn.bounds) {
            App.clickByBtn(nowSearchIconBtn, 5)
        } else {
            App.click(searchIconBtn.position.x, searchIconBtn.position.y, 5)
        }
        getCommenData.searUser(getCommenData.setting.collect_content || '42927231280')
    },
    searUser(xhsId) {
        let searchBtn = btnConfig.search.searchBtn
        let searchTabBtn = btnConfig.search.searchTabBtn
        setText(0, '')
        sleep(1000)
        if (!xhsId && !myUi.deviceInfo.xhsid) {
            getCommenData.taskConfig.errorTask = '未配置搜索用户id,且当前账户未绑定小红书号'
            return
        }
        if (xhsId) {
            setText(0, xhsId)
        } else {
            setText(0, myUi.deviceInfo.xhsid)
        }
        App.randomSleep(2, 4)
        //点击搜索按钮
        let nowSearchBtn = searchBtn.default()
        if (!nowSearchBtn) {
            console.log('搜索按钮不存在，请检查并手动复原重新启动');
            getCommenData.taskConfig.errorTask = '搜索按钮不存在'
            return
        }
        if (nowSearchBtn.bounds) {
            App.clickByBtn(nowSearchBtn, 3)
        } else {
            App.click(searchBtn.position.x, searchBtn.position.y, 3)
        }
        //切换到用户标签页
        let searchTab = searchTabBtn.default()
        if (!searchTab.length) {
            console.log('未查询到切换按钮，反馈异常')
            getCommenData.taskConfig.errorTask = '未查询到切换按钮'
            return
        }
        searchTab.forEach(element => {
            let userBtn = element.findOne(text('用户'))
            let userBtn2 = element.findOne(text('账号'))
            if (userBtn) {
                App.clickByBtn(userBtn, 2)
            }
            if (userBtn2) {
                App.clickByBtn(userBtn2, 2)
            }
        });
        App.randomSleep(2, 4)

        let userImgBtn = btnConfig.search.searchUserImg.default()
        if (!userImgBtn.length) {
            console.log('搜索后未返回用户头像列表，反馈异常');
            getCommenData.taskConfig.errorTask = '搜索后未返回用户头像列表'
            return
        }
        App.clickByBtn(userImgBtn[0], true)
        let setting = getCommenData.setting
        if (!setting.num) {
            console.log('任务配置参数异常，反馈异常');
            getCommenData.taskConfig.errorTask = '任务配置参数异常'
            return
        }
        if (setting.collect_content && setting.num) {
            getCommenData.getPostInfo({
                collect_id: setting.collect_id || '',
                postList: []
            }, setting.num)
        } else {
            getCommenData.taskConfig.errorTask = '任务配置参数异常，collect_content || num'
        }
    },
    /**
     * 
     * @param {*} postInfo // 帖子收集列表
     * @param {*} listNum  // 帖子收集数量

     * @returns 
     */
    getPostInfo(postInfo, listNum) {
        let data = getCommenData.data
        let endTime = data.time[1] * 1000 - 30000
        let nowTimeTask = new Date().getTime()
        console.log('任务结束日期：', new Date(endTime).toLocaleDateString() + new Date(endTime).toLocaleTimeString());
        let setting = getCommenData.setting
        let allPostInfo = postInfo
        let postList = btnConfig.user.userPostList.default()
        if (endTime <= nowTimeTask || getCommenData.taskConfig.taskStatus) {
            //任务已结束
            console.log('已到任务结束时间');
            getCommenData.savePostInfo = allPostInfo
            if (!getCommenData.taskConfig.taskStatus) {
                getCommenData.taskConfig.taskStatus = true
            }
            return
        }
        if (!postList) {
            console.log('未查询到帖子列表')
            allPostInfo.postList = []
            getCommenData.taskConfig.taskStatus = true
            return
        }
        let postItems = btnConfig.user.userPostItems.default()
        if (!postItems.length) {
            console.log('未查询到帖子')
            getCommenData.taskConfig.taskStatus = true
            return
        }
        if (listNum && listNum <= allPostInfo.postList.length || getCommenData.taskConfig.taskStatus) {
            console.log('帖子收集完毕')
            getCommenData.savePostInfo = allPostInfo
            if (!getCommenData.taskConfig.taskStatus) {
                getCommenData.taskConfig.taskStatus = true
            }
            return
        }
        //帖子列表循环遍历
        postItems.forEach((postView, index) => {
            let nowTime = new Date().getTime()
            if (endTime <= nowTime || listNum && listNum <= allPostInfo.postList.length) {
                console.log(endTime <= nowTime ? '任务超时，进行结束':'帖子收集完毕')
                getCommenData.savePostInfo = allPostInfo
                if (!getCommenData.taskConfig.taskStatus) {
                    getCommenData.taskConfig.taskStatus = true
                }
                return
            }
            let postDesc = postView.desc() || ''
            let like = postView.findOne(id('jfa'))
            if ((!like || like.text() == '赞') && setting.like_min * 1 > 0) {
                console.log('赞数不满足门槛，跳过此笔记');
                // 不满足赞数门槛
                return
            }
            console.log('NO：' + index + '当前帖子：' + postDesc);
            if (getCommenData.postViewList.findIndex(item => item == postDesc) == -1) {
                getCommenData.postViewList.push(postDesc)
                getCommenData.resolvePost(postView, allPostInfo, postDesc)
            }
        });
        if (listNum && listNum <= allPostInfo.postList.length) {
            console.log('帖子收集完毕')
            getCommenData.savePostInfo = allPostInfo
            if (!getCommenData.taskConfig.taskStatus) {
                getCommenData.taskConfig.taskStatus = true
            }
            return
        }
        //循环后滚动帖子列表查看更多帖子信息
        if (!postList.scrollable()) {
            console.log('帖子列表到底了-无其他帖子了')
            getCommenData.savePostInfo = allPostInfo
            if (!getCommenData.taskConfig.taskStatus) {
                getCommenData.taskConfig.taskStatus = true
            }
            return
        }


        if (postList.scrollForward()) {
            console.log('帖子列表滚动成功-翻页')
            App.randomSleep(2, 4)
            getCommenData.getPostInfo(allPostInfo, listNum)
        } else {
            getCommenData.savePostInfo = allPostInfo
            getCommenData.taskConfig.taskStatus = true
        }
    },
    resolvePost(postView, allPostInfo, title) {
        App.clickByBtn(postView, true)
        let infoDom = btnConfig.post.contentInfo.default(true)
        let infoDom2 = btnConfig.post.contentInfo2.default(true)
        let titleDom = btnConfig.post.titleInfo.default(true)
        let likeDom = className('android.widget.Button').descContains('点赞').find()
        let saveDom = className('android.widget.Button').descContains('收藏').find()
        let commentDom = className('android.widget.Button').descContains('评论').find()
        let shareBrn = btnConfig.post.shareBrn.default()

        let targetSave = (getCommenData.setting.save_min || 0) * 1
        let targeComment = (getCommenData.setting.comment_min || 0) * 1
        let targetLike = (getCommenData.setting.like_min || 0) * 1

        if (commentDom.length) {
            let nowIndex = commentDom.length > 2 ? 1 : 0;
            let postInfo = {
                link: "",
                title: titleDom.length ? titleDom[nowIndex].text() : title,
                content: infoDom.length ? infoDom[nowIndex].text() : infoDom2.length ? infoDom2[nowIndex].desc() : '',
                like_num: likeDom.length ? likeDom[nowIndex].desc().split('点赞')[1] * 1 : 0,
                save_num: saveDom.length ? saveDom[nowIndex].desc().split('收藏')[1] * 1 : 0,
                comment_num: commentDom.length ? commentDom[nowIndex].desc().split('评论')[1] * 1 : 0,
                comments: []
            }
            if (postInfo.save_num >= targetSave && postInfo.comment_num >= targeComment && postInfo.like_num >= targetLike) {
                console.log('满足条件帖子，开始收集评论');
                getCommenData.getLinke(shareBrn, postInfo)
                App.randomSleep(2, 4)
                if (postInfo.comment_num && commentDom[nowIndex]) {
                    let viewComment = []
                    if (commentDom[nowIndex].bounds) {
                        App.clickByBtn(commentDom[nowIndex], 3)
                    } else {
                        App.click(btnConfig.post.resolveBtn.position.x, btnConfig.post.resolveBtn.position.y, 3)
                    }
                    let page = 1
                    getCommenData.resolveCommentList(postInfo, viewComment, page)
                    back()
                    sleep(2000)
                }
                console.log('帖子详情：', postInfo);
                if (postInfo.comments && postInfo.comments.length > 0) {
                    //收集到了评论才上报
                    allPostInfo.postList.push(postInfo)
                }
            }
        } else {
            console.log('找不到帖子按钮信息');
            // getCommenData.taskConfig.errorTask += 1
        }
        App.randomSleep(2, 4)
        back()
        sleep(2000)
    },
    getLinke(shareBrn, postInfo) {
        if (shareBrn) {
            App.clickByBtn(shareBrn, 3)
            let moreBtnMenu = btnConfig.post.moreBtnMenu.default()
            let copyBtn = btnConfig.post.copyBtn.default()
            if (!moreBtnMenu) {
                console.log('找不到moreBtnMenu');
            }
            if (!copyBtn) {
                let scroll = true
                while (!copyBtn && scroll) {
                    try {
                        scroll = moreBtnMenu.scrollForward()
                        sleep(2000)
                        copyBtn = btnConfig.post.copyBtn.default()
                        sleep(2000)
                    } catch (error) {
                        scroll = false
                    }
                }
                if (!copyBtn) {
                    console.log('找不到复制链接按钮');
                }
            }

            if (copyBtn.bounds) {
                App.clickByBtn(copyBtn, true)
            } else {
                App.click(btnConfig.post.copyBtn.position.x, btnConfig.post.copyBtn.position.y, true)
            }

            // launch(Xhs.AppPackName)
            // sleep(1000)
            // postInfo['link'] = getClip() || ''
            // sleep(3000)
            // launch(Xhs.packName);
            let resolveInputBtn = btnConfig.post.resolveInputBtn.default()
            if (resolveInputBtn) {
                App.clickByBtn(resolveInputBtn, 3)
                let input = btnConfig.post.resolveInput.default() || btnConfig.post.resolveInput2.default()
                if (input) {
                    input.paste()
                    App.randomSleep(2, 4)
                    input = btnConfig.post.resolveInput.default() || btnConfig.post.resolveInput2.default()
                    postInfo['link'] = input ? input.text() : '查询文章链接失败'
                    setText('')
                    back()
                }
                sleep(2000)
            } else {
                console.log('找不到输入框');
            }
        } else {
            console.log('找不到分享按钮');
        }
    },
    resolveCommentList(postInfo, viewComment, page) {
        if (page >= Xhs.CommentPage) {
            console.log('评论页数超过设定值，停止收集：上限' + Xhs.CommentPage + '页')
            return
        }
        let setting = getCommenData.setting
        let commentList = btnConfig.post.commentList.default() || btnConfig.post.commentList2.default()
        if (!commentList) {
            console.log('找不到评论列表');
            postInfo.comments = []
            return
        }
        let commentItems = btnConfig.post.commentItem1.default()
        if (!commentItems.length) {
            postInfo.comments = []
            return
        } else {
            console.log('评论列表：', commentItems.length + '\n关键词：' + setting.collect_keyword);
        }
        commentItems.forEach((commentItem) => {
            let text = commentItem.findOne(id('jch'))
            let name = commentItem.findOne(id('jjo'))
            if (!text || !text.text()) {
                return
            }
            console.log('当前浏览评论用户: ' + name.text() + ' 内容: ' + text.text());
            //查询是否浏览过
            let findIndex = viewComment.findIndex((item) => {
                return item == name.text()
            })
            //未浏览过的用户评论，包含关键字匹配,收集
            if (findIndex == -1 && setting.collect_keyword.some((item)=>text.text().includes(item))) {
                viewComment.push(name.text())
                getCommenData.filterCommant(text.text(), commentItem, postInfo.comments)
            }
            sleep(1000)
        });
        console.log('scrollForward()', commentList.scrollable());
        if (commentList.scrollable()) {
            //可以滑动
            if (commentList.scrollForward()) {
                getCommenData.resolveCommentList(postInfo, viewComment, (page += 1))
            } else {
                console.log('滑动失败，没有更多评论了');
            }
        } else {
            console.log('没有更多评论了');
            //触底了
        }
    },
    filterCommant(commanText, commentItem, commentList) {
        if (commanText.includes('-') || commanText.includes('6天前')) {
            //超时，不涉及
            console.log('评论超时，不涉及 \n');
            return
        }
        let imgBtn = commentItem.findOne(id('e98'))
        if (!imgBtn) {
            console.log('找不到图片按钮');
            return
        }
        App.clickByBtn(imgBtn, 3)
        let userNick = btnConfig.user.userPageNick.default()
        let userLocation = btnConfig.user.userPageLocation.default()
        let userId = btnConfig.user.userPageId.default()

        if (userId) {
            let commentInfo = {
                content: commanText,
                xhsid: userId ? userId.text().replace('小红书号：', '') : '',
                nickname: userNick ? userNick.text() : '',
                avatar: "",
                ip: userLocation ? userLocation.text().replace('IP属地：', '') : '',
            }
            console.log('comments', commentInfo);
            commentList.push(commentInfo)
        }
        back()
        sleep(2000)

    }
}
module.exports = getCommenData